package cn.iocoder.yudao.module.biz.controller.admin.licence;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.biz.controller.admin.licence.vo.*;
import cn.iocoder.yudao.module.biz.controller.admin.licenceAudit.vo.BizLicenceAuditRespVO;
import cn.iocoder.yudao.module.biz.dal.dataobject.licence.BizLicenceDO;
import cn.iocoder.yudao.module.biz.dal.mysql.licence.BizLicenceMapper;
import cn.iocoder.yudao.module.biz.service.licence.BizLicenceService;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.minio.*;
import io.minio.errors.MinioException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Api(tags = "管理后台 - 危险作业票主")
@RestController
@RequestMapping("/biz/licence")
@Validated
public class BizLicenceController {

    @Resource
    private BizLicenceService licenceService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private BizLicenceMapper licenceMapper;

    @Resource
    DeptService deptService;

    @PostMapping("/create")
    @ApiOperation("创建危险作业票 第一次填写时使用")
    @DataPermission(enable = false)
    public CommonResult<String> createLicence(@Valid @RequestBody BizLicenceCreateReqVO createReqVO) {
        return success(licenceService.createLicence(getLoginUserId(), createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新危险作业票")
    @DataPermission(enable = false)
    public CommonResult<Boolean> updateLicence(@Valid @RequestBody BizLicenceUpdateReqVO updateReqVO) {
        licenceService.updateLicence(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除危险作业票")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    public CommonResult<Boolean> deleteLicence(@RequestParam("id") String id) {
        licenceService.deleteLicence(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得危险作业票")
    @DataPermission(enable = false)
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<BizLicenceRespVO> getLicence(@RequestParam("id") String id) {
        return success(licenceService.getLicence(id));
    }

    @GetMapping("/getLicenceAuditList")
    @ApiOperation("获得审批流程信息")
    @DataPermission(enable = false)
    public CommonResult<List<BizLicenceAuditRespVO>> getLicenceAuditList(@RequestParam("licenceId") String licenceId) {
        return success(licenceService.getLicenceAuditList(licenceId));
    }

    @PostMapping("/list")
    @ApiOperation("获得所有危险作业票列表")
    public CommonResult<List<BizLicenceRespVO>> getLicenceList(@RequestBody BizLicenceExportReqVO licenceExportReqVO) {
        return success(licenceService.getLicenceList(getLoginUserId(), licenceExportReqVO));
    }

    @GetMapping("/todo/list")
    @ApiOperation("获得当前用户待办作业票列表")
    @DataPermission(enable = false)
    public CommonResult<List<BizLicenceRespVO>> getTodoList() {
        return success(licenceService.getTodoList(getLoginUserId()));
    }

    @GetMapping("/page")
    @ApiOperation("获得危险作业票分页")
    public CommonResult<PageResult<BizLicenceRespVO>> getLicencePage(@Valid BizLicencePageReqVO pageVO) {
        return success(licenceService.getLicencePage(getLoginUserId(), pageVO));
    }

    @GetMapping("/audit")
    @ApiOperation("审核人员审核危险作业票")
    @DataPermission(enable = false)
    public CommonResult<String> auditLicence(@Valid BizLicenceAuditVO auditVO) {
        Boolean lastUser = licenceService.auditLicence(getLoginUserId(), auditVO);
        if (lastUser) {
            printPdf(auditVO.getLicenceId());
        }
        return CommonResult.success(auditVO.getLicenceId());
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出危险作业票主 Excel")
    @OperateLog(type = EXPORT)
    public void exportLicenceExcel(@Valid BizLicenceExportReqVO exportReqVO,
                                   HttpServletResponse response) throws IOException {

    }

    @GetMapping("/print/pdf")
    @ApiOperation("打印pdf")
    public void printPdf(String licenceId) {

        PrintPdfVO printPdfVO = licenceService.printPdf(licenceId);
        try {
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(printPdfVO.getOssEndpoint())
                            .credentials(printPdfVO.getOssAccessKey(), printPdfVO.getOssSecretKey())
                            .build();
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(printPdfVO.getOssBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(printPdfVO.getOssBucketName()).build());
            }

            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(printPdfVO.getOssBucketName())
                            .object(printPdfVO.getTargetPath())
                            .filename(printPdfVO.getFilepath())
                            .contentType("application/pdf")
                            .build());
            String url = printPdfVO.getOssEndpoint() + "/" + printPdfVO.getOssBucketName() + "/" + printPdfVO.getTargetPath();
            System.out.println("---------------------------");
            System.out.println(url);
            BizLicenceDO bizLicenceDO = licenceMapper.selectById(licenceId);
            bizLicenceDO.setPdfUrl(url);
            licenceMapper.updateById(bizLicenceDO);
        } catch (MinioException | InvalidKeyException | NoSuchAlgorithmException e) {
            System.out.println("Error occurred: " + e);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/submit")
    @ApiOperation("提交审核")
    public CommonResult<String> submit(@RequestParam String licenceId) throws IOException {
        return success(licenceService.submit(licenceId));
    }

    @GetMapping("/get/user")
    @ApiOperation("获取当前用户信息")
    @DataPermission(enable = false)
    public CommonResult<BizLoginUser> getLoginUser() {
        BizLoginUser bizLoginUser = new BizLoginUser();
        AdminUserDO adminUserDO = adminUserService.getUser(getLoginUserId());
        if (adminUserDO == null) {
            return CommonResult.error(1, "获取不到当前用户");
        }
        bizLoginUser.setUserName(adminUserDO.getUsername());

        long deptId = adminUserDO.getDeptId();
        DeptDO deptDO = deptService.getDept(deptId);
        if (deptDO != null) {
            bizLoginUser.setUserDeptName(deptDO.getName());
        }
//        bizLoginUser.setUserId(getLoginUserId());
        return success(bizLoginUser);
    }
}
